<template>
  <div class="my-upload">
    <h3 class="my-plus">+</h3>
    <img v-if="imgUrl" class="my-img" :src="imgUrl" alt />
    <input type="file" @change="changeFile" />
  </div>
</template>

<script>
import path from "path";
export default {
    data(){
        return {
            imgUrl:""
        }
    },
  methods: {
    //修改图
    changeFile(e) {
      //得到文件
      let file = e.target.files[0];

      // 判断大小 1M=1024kb 1kb=1024b
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件最大2M");
        return;
      }

      // 判断文件类型
      let imgArr = [".jpg", ".jpeg", ".png", ".gif"];

      /*let name=file.name ;// "1.1.1.1.1.jpg"
      let extname=name.slice(name.lastIndexOf("."));*/

      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      //根据文件生成一个图片地址
      this.imgUrl = URL.createObjectURL(file);

      //给form.img,将file传递给父组件
      this.$emit("sendFile",file)
      
    },
  },
};
</script>

<style lang="less">
@import "../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @header-color;
  position: relative;
}
.my-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
  color: @primary;
}
.my-img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
.my-upload input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}
</style>